package com.smartrobot.smartrobot.adapter;


import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.BaseAdapter;

import android.widget.LinearLayout;
import android.widget.ListView;

import android.widget.RelativeLayout;
import android.widget.TextView;

import com.huanxinapi.activity.ChatAllHistoryFragment;
import com.nostra13.universalimageloader.core.ImageLoader;

import com.smartrobot.smartrobot.R;
import com.smartrobot.smartrobot.activity.*;
import com.smartrobot.smartrobot.circle.CircleUtil;
import com.smartrobot.smartrobot.circle.FriendList;
import com.smartrobot.smartrobot.circle.NewFriend.NewFriendUtil;
import com.smartrobot.smartrobot.circle.commonData;
import com.smartrobot.smartrobot.logToSdCard.LogToSd;

import com.smartrobot.smartrobot.pojo.circleDetailPojo;
import com.smartrobot.smartrobot.pojo.getFriendListPojo;
import com.smartrobot.smartrobot.pojo.saveFriendListPojo;

import com.smartrobot.smartrobot.util.HttpUtil;
import com.smartrobot.smartrobot.util.ImageLoaderApi;

import com.smartrobot.smartrobot.util.PeopleRegisterMsg;
import com.smartrobot.smartrobot.util.User;

import com.smartrobot.smartrobot.view.ExTopListView;
import com.smartrobot.smartrobot.view.ExlistenListView;
import com.smartrobot.smartrobot.view.ToastCustom;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2014/12/23.
 */
public class SocialListViewAdapter extends BaseAdapter implements View.OnClickListener {


    private Context context;

    private RelativeLayout myBarberLayout,soc_content,soc_content_loading,myCircleFriendLayout;
    private LinearLayout new_friend_ly,circle_detail_ly;
    public TextView new_friend_tip;
    public static SocialListViewAdapter instance;
    private ExTopListView listView;


    private ListView my_barber_list,my_friend_list,my_circle_friend_list;
    public FriendViewAdapter friendAdapter,barberAdapter,circleAdapter;
    public static  Handler getFriendListHandler ;
    private final Handler readFileHandler = new Handler();
    private FriendList friendList ;
    private static boolean  isGettingFriendList = false;

    public List<getFriendListPojo> f_list,c_list,b_list;
    circleDetailPojo c_pojo;
    private final static int RETURN_FROM_ADD_ACTIVITY = 10;


    public SocialListViewAdapter(Context context,ExTopListView listView){

        this.context = context;


        this.listView = listView;

        instance = this;
    }

    @Override
    public int getCount() {
        return 1;
    }

    @Override
    public Object getItem(int i) {
        return i;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {

        convertView = LayoutInflater.from(context).inflate(R.layout.page_social_circle_my_circle, viewGroup, false);



        init(convertView);
        
        return  convertView;



    }




    public void init(View view) {


            Log.e("初始化view！！！！","");

            new_friend_ly = (LinearLayout) view.findViewById(R.id.new_friend_activity);

            new_friend_tip = (TextView) view.findViewById(R.id.new_friend_tip);


            circle_detail_ly = (LinearLayout) view.findViewById(R.id.circle_detail_activity);
            my_barber_list = (ListView) view.findViewById(R.id.my_barber_list);


            my_friend_list = (ListView) view.findViewById(R.id.my_friend_list);

            my_circle_friend_list = (ListView) view.findViewById(R.id.circle_friend_list);
            myBarberLayout = (RelativeLayout) view.findViewById(R.id.top1);
            myCircleFriendLayout = (RelativeLayout) view.findViewById(R.id.top3);
            myBarberLayout.setVisibility(View.GONE);
            myCircleFriendLayout.setVisibility(View.GONE);
            soc_content = (RelativeLayout) view.findViewById(R.id.soc_content);
            soc_content_loading = (RelativeLayout)view.findViewById(R.id.soc_content_loading);

            //内容消失
            soc_content.setVisibility(View.GONE);

            //loading显示
            soc_content_loading.setVisibility(View.VISIBLE);

            f_list = new ArrayList<getFriendListPojo>();
            b_list = new ArrayList<getFriendListPojo>();
            c_list = new ArrayList<getFriendListPojo>();

            getFriendListHandler = new changeFriendListHandler();


            ImageLoader.getInstance().init(ImageLoaderApi.getImageLoaderConfig(context));


            circle_detail_ly.setOnClickListener(this);
            new_friend_ly.setOnClickListener(this);


            newFriendTip();
            initAdapter();
            getCircleMsgFromLocal();
//        }
    }
        
            /*设置新消息的提醒*/
    public void newFriendTip(){
        if(new_friend_tip!=null){
            NewFriendUtil newFriendUtil = new NewFriendUtil(context);
            if(!newFriendUtil.getNewFriendTip().equals("")){
                new_friend_tip.setVisibility(View.VISIBLE);

                if(MainActivity.instance!=null){
                    MainActivity.instance.notiNewSocial();
                }

            }else{
                new_friend_tip.setVisibility(View.GONE);
                if(MainActivity.instance!=null){
                    MainActivity.instance.hideNewSocial();
                }
            }

        }

    }

    /*获取朋友列表*/
    protected void getCircleMsgFromLocal() {
        Thread t = new Thread() {
            public void run() {
                try{

                    if(User.getInstance()==null){
                        User.getUserInfo(context);
                    }
                    Log.e("=======用户的id",User.getInstance().getId());
//                    saveFriendListPojo list = (saveFriendListPojo)FileUtil.ReadCircleMsgFromFile(CommonFunc.stringToMD5(User.getInstance().getId() + Common.f_circle_friend),context); //处理得到结果了，这里一些内容保存在主类的成员变量中
                    saveFriendListPojo list = CircleUtil.getFriendList(context,User.getInstance().getId());

                    if(list!=null){
                        b_list = list.getBarberList();
                        f_list = list.getFriendList();
                        c_list = list.getCircleList();
                        readFileHandler.post(updateUiFromLocal); //告诉UI线程可以更新结果了
                    }else{
                        readFileHandler.post(updateUiFromServer); //告诉UI线程可以更新结果了

                    }

                }catch (Exception e){
                    LogToSd.log_init();
                    LogToSd.error("getCircleMsgFromLocal 出错");
                    LogToSd.error(e.toString());
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }


    public void getCircleMsgFromServer(){
            Thread t = new Thread(){
                @Override
                public void run() {
                    readFileHandler.post(updateUiFromServer); //告诉UI线程可以更新结果了
                }
            };
        t.start();
    }


    final Runnable updateUiFromLocal = new Runnable() {
        public void run() {
            Log.e("=====从本地读取=====","！！！！！！");
            adapterChange();
        }
    };




    final Runnable updateUiFromServer = new Runnable() {
        @Override
        public void run() {
            Log.e("=====从服务器取=====","！！！！！！");
            getFriend();

        }
    };



    final Runnable friendChangeRun = new Runnable() {
        @Override
        public void run() {
            Log.e("=====从服务器取=====","！！！！！！");
            friendAdapter.notifyFriendChange(f_list);

        }
    };



    public void getFriend(){
        if(!isGettingFriendList){
            friendList  = new FriendList();
            friendList.getFriendList(getFriendListHandler,context);
            isGettingFriendList = true;
        }
    }



    /*提醒更新*/
    public void adapterChange(){
        //内容显示
        soc_content.setVisibility(View.VISIBLE);

        //loading消失
        soc_content_loading.setVisibility(View.GONE);
        barberAdapter.notifyChange(b_list,my_barber_list);
        friendAdapter.notifyChange(f_list,my_friend_list);
        circleAdapter.notifyChange(c_list,my_circle_friend_list);
        if(User.getInstance().getRole().equals("客户")){
            myBarberLayout.setVisibility(View.VISIBLE);
            myCircleFriendLayout.setVisibility(View.VISIBLE);
        }else{
            myBarberLayout.setVisibility(View.GONE);
            myCircleFriendLayout.setVisibility(View.GONE);
        }


    }


    public void friendAdapterChange(){
        if(f_list!=null)
            readFileHandler.post(friendChangeRun);
    }

    @Override
    public void onClick(View v) {


        switch(v.getId()){

            case R.id.social_circle_add_friend:
                Intent intent = new Intent();
                intent.setClass(context,SocialAddActivity.class);
                context.startActivity(intent);
                break;

            case R.id.circle_detail_activity:
                Intent c_intent = new Intent();
                c_intent.setClass(context,Soc_detail_activity.class);
                c_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(c_intent);
                break;
            case R.id.new_friend_activity:

                /*消除新朋友提醒*/
                NewFriendUtil newFriendUtil = new NewFriendUtil(context);
                newFriendUtil.saveNewFriendTip("");
                new_friend_tip.setVisibility(View.GONE);

                /*跳转*/
                Intent n_intent = new Intent();
                n_intent.setClass(context, New_friend_activity.class);
                context.startActivity(n_intent);
                break;
        }
    }


    public static  void changeFriendList(int requestCode, int resultCode, Intent data){
        Log.e("==============================从新改变朋友列表=======================","");
        if(resultCode == 10) {
            Log.e("开始改变！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！","");
            if(instance!=null){
                instance.getCircleMsgFromLocal();
            }else{
                CircleUtil.isFriendChange = false;
            }
        }
    }




    //handle 处理
    class changeFriendListHandler extends Handler {

        @Override
        public void dispatchMessage(Message msg) {
            isGettingFriendList = false;
            listView.changeState();

            if(msg.what== commonData.SHOW_FRIEND_TIP_NUM){

                switch (msg.arg1){
                    case 0:

                        if(new_friend_tip!=null){
                            new_friend_tip.setVisibility(View.GONE);
                            if(MainActivity.instance!=null){
                                MainActivity.instance.hideNewSocial();
                            }
                        }
                        break;
                    case 1:

                        if(new_friend_tip!=null){
                            new_friend_tip.setVisibility(View.VISIBLE);

                            if(MainActivity.instance!=null){
                                MainActivity.instance.notiNewSocial();
                            }
                        }
                        break;
                }

            }

            //链接服务器失败
            if(msg.what == commonData.CAN_NOT_CONNECT_SERVER_CODE){

                ToastCustom.showToast(context, msg.obj.toString());
                isGettingFriendList = false;
                return;
            }

            if(msg.what==commonData.SHOW_TIP_CODE){
                ToastCustom.showToast(context,msg.obj.toString());
                isGettingFriendList = false;

                return;
            }

            //获取好友列表成功
            if(msg.what == commonData.GET_FRIEND_LIST_SUCCESS_CODE)
            {
                try{
                    Map<String, Object> f_pojo_map = new HashMap<String, Object>();
                    f_pojo_map = (Map<String,Object>)msg.obj;

                    f_list = (ArrayList<getFriendListPojo>)f_pojo_map.get("friendList");

                    c_list =  (ArrayList<getFriendListPojo>)f_pojo_map.get("customerList");

                    b_list =  (ArrayList<getFriendListPojo>)f_pojo_map.get("barberList");

                    String role = f_pojo_map.get("role").toString();


                    adapterChange();
                    isGettingFriendList = false;

                    if(ChatAllHistoryFragment.instance != null)
                    ChatAllHistoryFragment.instance.notiDataChange();



                }catch (Exception e){
                    e.printStackTrace();
                    LogToSd.debug(e.getMessage());
                }

                return;
            }



            //获取好友失败
            if(msg.what == commonData.GET_FRIEND_LIST_FAIL_CODE)
            {
                isGettingFriendList = false;
                return;
            }


            //获取圈子详情成功
            if(msg.what == commonData.GET_CIRCLE_DETAIL_SUCCESS_CODE){
                c_pojo = new circleDetailPojo();
                c_pojo = (circleDetailPojo)msg.obj;


                return;
            }





            //数据异常
            if(msg.what ==commonData.DATA_ERROR_CODE){
                isGettingFriendList = false;
                return;
            }


            //用户未登录
            if(msg.what==commonData.USE_NOT_LOGIN_CODE){
                //帮组用户登录
                isGettingFriendList = false;
                int flag = msg.arg1;
                if (User.getInstance() != null&&!User.getInstance().getId().equals("未填写") ) {
                    HttpUtil.apiLogin(context, new PeopleRegisterMsg(User.getInstance().getPhone(), User.getInstance().getPwd()), getFriendListHandler, flag);

                } else if (User.getUserInfo(context)&&!User.getInstance().getId().equals("未填写")) {
                    HttpUtil.apiLogin(context, new PeopleRegisterMsg(User.getInstance().getPhone(), User.getInstance().getPwd()), getFriendListHandler,flag);
                } else {
                    ToastCustom.showToast(context, "请登录！");
                }
                return;
            }

            if(msg.what== HttpUtil.LOGIN_SUCCESS){
                getFriend();
            }

        }
    }


    public  void initAdapter(){
        try{
            f_list = new ArrayList<getFriendListPojo>();
            c_list = new ArrayList<getFriendListPojo>();
            b_list = new ArrayList<getFriendListPojo>();
            barberAdapter = new FriendViewAdapter(context,b_list);
            circleAdapter = new FriendViewAdapter(context,c_list);
            friendAdapter = new FriendViewAdapter(context,f_list);
            my_barber_list.setAdapter(barberAdapter);
            my_friend_list.setAdapter(friendAdapter);
            my_circle_friend_list.setAdapter(circleAdapter);

            my_barber_list.setOnItemClickListener(barberAdapter);
            my_friend_list.setOnItemClickListener(friendAdapter);
            my_circle_friend_list.setOnItemClickListener(circleAdapter);
        }catch (Exception e){
            e.getStackTrace();
            LogToSd.debug("初始化适配器错误");
            Log.e("----------------->",e.getMessage());
        }

    }





}
